package com.supermap.geometry;

import com.supermap.geometry.serverservice.GetDatasetImpl;
import io.grpc.ServerBuilder;

import java.io.IOException;
import java.util.logging.Logger;

/**
 * @author liqs
 * @version 1.0
 * @date 2021/10/21 11:00
 */
public class GeometryServer {
    private static final Logger logger = Logger.getLogger(GeometryServer.class.getName());

    /* The port on which the server should run */
    private int port = 50052;
    private io.grpc.Server server;

    /**
     * Main launches the server from the command line.
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        GeometryServer geometryServer = new GeometryServer();
        geometryServer.start();
        geometryServer.blockUntilShutdown();
    }

    private void start() throws IOException {

        /**
         * 可根据实际需要构造多个
         */
        GetDatasetImpl getDataset = new GetDatasetImpl();

        server = ServerBuilder.forPort(port)
                .addService(getDataset)
                .build()
                .start();
        logger.info("Server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                GeometryServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * Await termination on the main thread since the grpc library uses daemon threads.
     */
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

}
